package com.example.demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.pojo.User;
import com.example.demo.service.Uservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private Uservice userService;
    @PostMapping("/saveOrUpdate")
    public boolean saveOrUpdate(@RequestBody User user) {
        return userService.saveOrUpdateById(user);
    }
    @GetMapping("/page")
    public Page<User> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String username) {
        return userService.page(current, size, username);
    }
    @DeleteMapping("/deleteBatch")
    public boolean deleteBatchIds(@RequestBody List<Long> ids) {
        return userService.deleteBatchIds(ids);
    }
    @GetMapping("/getByUsername")
    public User getUserByUsername(@RequestParam String username) {
        return userService.getUserByUsername(username);
    }
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        boolean success = userService.register(user);

        if (success) {
            result.put("code", 200);
            result.put("message", "注册成功");
        } else {
            result.put("code", 400);
            result.put("message", "用户名已存在");
        }
        return result;
    }
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> params) {
        String username = params.get("username");
        String password = params.get("password");

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> loginResult = userService.login(username, password);

        if (loginResult != null) {
            result.put("code", 200);
            result.put("message", "登录成功");
            result.put("data", loginResult);
        } else {
            result.put("code", 401);
            result.put("message", "用户名或密码错误");
        }
        return result;
    }
}